package net.dodoman.shape;

import java.io.BufferedReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.driver.OracleResultSet;
import oracle.sql.CLOB;

public class ReadClob {

	public ReadClob() {

	}

	public static final Connection getDataBaseConnection()

	throws SQLException {
		Connection conn = null;
		// URL
		String dbUrl = "";
		// 用户名
		String user = "feiyangnew";
		// 密码
		String password = "feiyang";
		// 驱动
		String driver = "oracle.jdbc.driver.OracleDriver";
		try {
			Class.forName(driver);
			String url = dbUrl;
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 
	 * 向库中加Clob值
	 * 
	 * @param policyinfo
	 *            所加内容
	 * 
	 */

	public void addClob(String policyinfo) {
		String sql = "insert into TEST_CLOB (test,id) values( empty_clob(),'2')";
		try {
			Connection conn = getDataBaseConnection();
			// 不允许自动提交
			conn.setAutoCommit(false);
			Statement stmt = conn.createStatement();
			// 先插一个空值
			boolean boo = stmt.execute(sql);
			String str = "select test from TEST_CLOB where id = '2' for update";
			Statement stmt_ = conn.createStatement();
			ResultSet rs = stmt_.executeQuery(str);
			CLOB clob = null;
			if (rs.next()) {
				clob = ((OracleResultSet) rs).getCLOB(1);
				clob.putString(1, policyinfo);
				// 更新该字段
				sql = "update TEST_CLOB set test=? where id='2' ";
				PreparedStatement pstmt = conn.prepareStatement(sql);
				pstmt.setClob(1, clob);
				pstmt.executeUpdate();
				pstmt.close();
			}
			conn.commit();
			rs.close();
			stmt_.close();
			stmt.close();
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * 读取Clob
	 * 
	 * @throws java.lang.Exception
	 * 
	 */

	public void readClob() throws Exception {
		String str = "select test from TEST_CLOB";
		Connection conn = getDataBaseConnection();
		Statement stmt = conn.createStatement();
		ResultSet rs = null;
		CLOB clob = null;
		for (rs = stmt.executeQuery(str); rs.next();) {
			clob = (((OracleResultSet) rs).getCLOB(1));
			// clob = ( ( ( OracleResultSet ) rs ).getCLOB ( "test" ) );
			if (clob != null) {
				Reader is = clob.getCharacterStream();
				BufferedReader br = new BufferedReader(is);
				String s = br.readLine();
				System.out.println("START:" + s);
				String content = "";
				while (s != null) {
					content += s;
					s = br.readLine();
					System.out.println("content::" + content);
					System.out.println("SSS:::" + s);
				}
				br.close();
				is.close();
			}
		}
		rs.close();
		stmt.close();
		conn.close();
	}

}
